<template>
    <selectFromBank v-if="showItemBank">
        <template #comfirmSelect>
            <el-button type="primary" @click="comfirmSelect">确认选择</el-button>
        </template>
        <template #checkBox="{ row }">
            <!-- 注意这里我们不再使用 :checked 绑定，而是使用 :model-value 来确保响应性 -->
            <el-checkbox :model-value="isItemSelected(row.id)" @click.stop="handleCheckAllChange(row)">选择</el-checkbox>
        </template>
        <template #backToPaper="{ row }">
            <el-col :span="4">
                <el-button plain type="danger" @click="showItemBank = !showItemBank">返回试卷</el-button>
            </el-col>
        </template>
    </selectFromBank>
    <div v-else class="outerbox">
        <el-card class="box-card">
            
            <template #header>
                <div class="card-header">
                    <h3>试卷管理</h3>
                    <div class="button_group">
                        <el-button @click="backToList" type="primary" plain size="small">返回试卷列表</el-button>
                        <el-button @click="openItemBank" type="primary" plain size="small">从试题库选择</el-button>
                        <el-button @click="deleteItems" type="primary" plain size="small">批量删除</el-button>
                        <paperExport :paperId="paperId" class="custom-component" />
                    </div>
                </div>
            </template>
            <addItem @refreshAfterEdit="getItemsOfPaper" ref="addItemRef"></addItem>
            <div v-loading="loading" class="middleBox">
                <div v-for="item in itemList" :key="item.id" class="card-item">
                    <div class="item-content">
                        <div class="item-actions">
                            <el-button @click="editItem(item)" circle plain :icon="Edit" type="primary"
                                size="mini"></el-button>
                            <el-button @click="deleteItem(item)" circle plain :icon="Delete" type="danger"
                                size="mini"></el-button>
                        </div>
                        <el-checkbox class="item-checkbox" v-model="item.checked"></el-checkbox>
                        <div v-html="item.questionContent" class="item-question"></div>
                        <div v-if="item.type === '选择题' || item.type === '多项选择题' || item.type === '多选题' || item.type === '单项选择题'"
                            class="item-options">
                            <!-- 选项： -->
                            <ul class="item-options-list">
                                <li class="item-option" v-for="(option, index) in item.options" :key="option">
                                    <span class="item-option-circle">{{ String.fromCharCode(65 + index) }}</span>
                                    <span v-html="option" class="item-option-value"></span>
                                    <!-- <span class="item-option-value">{{ option }}</span> -->
                                </li>
                            </ul>
                        </div>
                        <div class="item-info">
                            <div class="item-header">
                                <div class="item-score">分值：{{ item.score }}</div>
                                <div class="item-type">题型：{{ item.type }}</div>
                            </div>
                            <div class="wrapper">
                                <span style="font-size: 12px;">答案：</span>
                                <span v-html="item.answer" class="item-answer"></span>
                            </div>

                            <div class="item-difficulty">难度：{{ item.difficulty }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>Footer content</template>
        </el-card>
    </div>
    <!-- <pie></pie> -->
</template>

<script setup>
import addItem from '../itemBank/addItem.vue'
import selectFromBank from '@/components/selectFromBank.vue'
import pie from '@/components/pie.vue'
import { onMounted, ref } from 'vue'
import { Plus, Check, CircleCheck, Grid, HelpFilled, Finished, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus';
import { AddItemToPaper, delItemsInPaper, PaperGetItemDetail } from '@/api/paper'
import paperExport from '@/components/paperExport.vue'
const addItemRef = ref()
const showItemBank = ref(false)
const loading = ref(false)
const itemList = ref([])
const selectedItems = ref([]);

import { useRoute, useRouter } from 'vue-router';
// const subId = parseInt(route.params.subId)
const router = useRouter();
// 返回试卷列表
const backToList = () => {
    router.push({
        name: "paperList",
    });
}
// 获取试卷题目
const route = useRoute()
const paperId = parseInt(route.params.paperId)
const paperDetailItems = ref([])
const getItemsOfPaper = async(data) => {
    // console.log("触发一次获取试卷题目", data);
    const res = await PaperGetItemDetail(paperId)
    paperDetailItems.value = res.data.data
    itemList.value = paperDetailItems.value
    // console.log("finished");
}
onMounted(() => {
    getItemsOfPaper()
})
// 在setup函数中初始化一个用来跟踪勾选状态的Map
const selectedMap = ref(new Map());

// 修改isItemSelected函数，使用selectedMap来判断题目是否被选中
const isItemSelected = (itemId) => {
    return selectedMap.value.get(itemId) || false;
};
// 重置选择状态的函数
const resetSelection = () => {
    selectedMap.value.clear(); // 清空Map
    selectedItems.value = []; // 清空已选题目数组
};
// 打开题库选择界面的函数
const openItemBank = () => {
    resetSelection(); // 调用重置函数
    showItemBank.value = true; // 显示题库选择组件
};
// 获取所有选择的题目
// 修改handleCheckAllChange函数，更新selectedMap的状态而不是直接修改row对象
const handleCheckAllChange = (row) => {
    if (selectedMap.value.get(row.id)) {
        selectedMap.value.delete(row.id);
        const index = selectedItems.value.findIndex(item => item.id === row.id);
        if (index !== -1) {
            selectedItems.value.splice(index, 1);
        }
    } else {
        selectedMap.value.set(row.id, true);
        selectedItems.value.push(row);
    }
};
// 确认选择按钮  批量从试题库添加题目
const comfirmSelect = async () => {
    showItemBank.value = false
    console.log("selectedItems.value", selectedItems.value);
    selectedItems.value.forEach((item) => {
        item.checked = false;
    });
    selectedItems.value.map((item) => {// 选择的数据赋值给试卷数据源
        itemList.value.push(item)
    })
    console.log("itemList.value", itemList.value);
    const newArray = itemList.value.map(obj => {
        return {
            paperId,
            questionId: obj.id
        }
    })
    const dataSaveToPaper = {
        data: newArray
    }
    await AddItemToPaper(dataSaveToPaper)
    itemList.value = paperDetailItems.value
    selectedItems.value = []
}


const editItem = (item) => {
    addItemRef.value.open(item)
    getItemsOfPaper()
}
// 删除单个题目
const deleteItem = (item) => {
    ElMessageBox.confirm(`确定删除这道题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            const dataSaveToPaper = {
                data: [{
                    paperId,
                    // paperId: 1,
                    questionId: item.id
                }]
            }
            await delItemsInPaper(dataSaveToPaper)
            itemList.value.splice(itemList.value.indexOf(item), 1)
        })
        .catch(() => {
        });
}

// 批量删除题目
const deleteItems = () => {
    const checkedItems = ref([])
    checkedItems.value = itemList.value.filter((item) => item.checked)
    if (checkedItems.value.length === 0) {
        return
    }
    ElMessageBox.confirm(`确定删除所选题目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            const newArray = checkedItems.value.map(obj => {
                return {
                    paperId,
                    questionId: obj.id
                }
            })
            const dataSaveToPaper = {
                data: newArray
            }
            // console.log("dataSaveToPaper 删除的", dataSaveToPaper);
            await delItemsInPaper(dataSaveToPaper)
            checkedItems.value.forEach((item) => {
                itemList.value.splice(itemList.value.indexOf(item), 1)
            })
        })
        .catch(() => {
        });
}

</script>


<style scoped lang="scss">
.outerbox {
    display: flex;
}

.card-header {
    .button_group {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .custom-component {
            margin-left: 13px;
        }
    }
}

.box-card {
    // display: flex;
    width: 900px;
    height: 900px;
    overflow: auto;

    &::-webkit-scrollbar {
        width: 5px;
    }

    &::-webkit-scrollbar-thumb {
        background-color: #e7e9ec;
        /* 设置滚动条滑块颜色 */
        border-radius: 4px;
        /* 设置滚动条滑块圆角 */
    }

    .card-item {
        margin-bottom: 18px;
        padding: 10px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        background-color: rgb(245, 247, 250);
        position: relative;

        .item-content {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: flex-start;
            gap: 10px;

            .item-question {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 10px;
            }

            .item-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                gap: 20px;

                .item-type {
                    font-size: 12px;
                    color: #909399;
                    border-radius: 2px;
                }
            }

            .item-answer,
            .item-tags,
            .item-type,
            .item-score,
            .item-difficulty {
                font-size: 12px;
                margin-top: 5px;
            }

            .item-option-value {
                font-size: 12px;
                // margin-top: 5px;
            }

            .item-options-list {
                list-style: none;
                padding-left: 0;
                margin-top: 5px;

                .item-option {
                    display: flex;
                    align-items: center;
                    font-size: 12px;
                    margin-top: 3px;

                    .item-option-circle {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        width: 20px;
                        height: 20px;
                        border: 1px solid #ccc;
                        border-radius: 50%;
                        margin-right: 5px;
                        color: #909399;
                    }
                }
            }

            .item-actions {
                display: flex;
                align-items: flex-start;
                gap: 10px;
                position: absolute;
                top: 10px;
                right: 10px;
            }

            .item-checkbox {
                margin-right: 10px;
            }
        }
    }
}
</style>